package com.qf.proxy;

import org.springframework.cglib.proxy.Enhancer;
import org.springframework.cglib.proxy.MethodInterceptor;
import org.springframework.cglib.proxy.MethodProxy;

import java.lang.reflect.Method;

// cglib动态代理: 通过继承被代理类,来实现代理对象
public class CglibProxy implements MethodInterceptor {

    private Object obj;

    public CglibProxy(Object obj) {
        this.obj = obj;
    }

    @Override
    public Object intercept(Object o, Method method, Object[] objects, MethodProxy methodProxy) throws Throwable {
        System.out.println("开启事务(cglib)");
        try {
            Object result = method.invoke(obj, objects);
            System.out.println("提交事务(cglib)");
            return result;
        } catch (Exception e) {
            e.printStackTrace();
            System.out.println("回滚事务(cglib)");
            return null;
        }
    }


    public Object getProxyInstance(){
        Enhancer enhancer = new Enhancer();
        enhancer.setSuperclass(obj.getClass());
        enhancer.setCallback(this);
        return enhancer.create();
    }

}
